package com.mysecurity.filter;

import com.alibaba.fastjson.JSON;
import com.mysecurity.pojo.SecurityUser;
import com.mysecurity.utils.Constants;
import com.mysecurity.utils.JWTAuth;
import com.mysecurity.utils.JedisUtil;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import redis.clients.jedis.Jedis;

import javax.security.sasl.AuthenticationException;
import java.io.IOException;

/**
 * @author Jane
 * @date 2024-07-10 17:28
 */
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader(Constants.SECURITY_TOKEN_HEADER);

        System.out.println("token: "+ token);

        if (StringUtils.isNullOrEmpty(token)){
            //没有token,就放行
            filterChain.doFilter(request,response);
            return;
        }else{

            String userId = JWTAuth.parseJWTSubject(token);
            if (StringUtils.isNullOrEmpty(userId)){
                throw  new AuthenticationException("非法token");
            }

            //redis中检查该id的用户是否已经登录过,判断token是否过期
            //从redis中获取id为 userId 的用户,如果用户是空的,就抛异常,token失效,请重新登录
            String cacheUser="";
            Jedis jedis =null;
            try {
                jedis = JedisUtil.getJedis();
                if (null!=jedis ){
                    cacheUser = jedis.get(JWTAuth.KEY_REDIS_AUTH_USER + userId);
                }
            } catch (Exception e) {
                throw new AuthenticationException("登录已过期,请重新登录");
            } finally {
                JedisUtil.close(jedis);
            }

            //否则就存入UsernamePasswordAuthenticationToken

            SecurityUser securityUser = JSON.parseObject(cacheUser, SecurityUser.class);
            if (null == securityUser){
                throw new AuthenticationException("登录信息已失效,请重新登录");
            }

            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(securityUser,null,securityUser.getAuthorities());

            //放回上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            System.out.println("-----------------JwtRequestFilter");
            filterChain.doFilter(request,response);

        }


    }
}
